<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>基本资料</span>
    </div>
    <!-- 表单 -->
    <el-form
      label-position="left"
      label-width="80px"
      :model="userInfo"
      :rules="userRules"
      ref="formRef"
    >
      <el-form-item label="登录名称">
        <el-input disabled v-model="userInfo.username"></el-input>
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickname">
        <el-input v-model="userInfo.nickname"></el-input>
      </el-form-item>
      <el-form-item label="用户邮箱" prop="email">
        <el-input v-model="userInfo.email"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="modifyInfo">提交修改</el-button>
        <el-button @click="$refs.formRef.resetFields()">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
export default {
  name: "UserInfo",
  data() {
    return {
      userInfo: {
        ...this.$store.state.user,
      },
      // 表单的验证规则对象
      userRules: {
        nickname: [
          { required: true, message: "请输入用户昵称", trigger: "blur" },
          {
            pattern: /^\S{1,10}$/,
            message: "昵称必须是1-10位的非空字符串",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入用户邮箱", trigger: "blur" },
          { type: "email", message: "邮箱格式不正确", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    modifyInfo(){
       //(1)检查表单是否校验成功
      this.$refs.formRef.validate(async (valid) => {
        // valid 就是表单验证的结果，如果是true，表示通过了
        console.log(valid);
        //(2)如果成功,则发送注册ajax
        if (valid) {
          //解构赋值 const {属性名:属性值}=对象名
          const {data:res} = await this.$axios.put('/my/userinfo',this.userInfo)
         console.log(res);
         if (res.code===0) {
          this.$message.success(res.message)
          this.$store.dispatch('getUserInfo')
         } else {
          this.$message.warning(res.message)
         }
         }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.el-form {
  width: 500px;
}
</style>
